<template>
  <div>
    <h3 style="text-align: center;">档案名称：【{{ archive.name }}】</h3>
    <el-table :data="archiveList">
      <el-table-column label="档号" align="center" prop="danghao" />
      <el-table-column label="射频标签号" align="center" prop="rfid" />
      <el-table-column label="保密级别" align="center" prop="secretLevel">
        <template #default="scope">
          <dict-tag :options="iams_secret_level" :value="scope.row.secretLevel" />
        </template>
      </el-table-column>
      <el-table-column label="保密期限" align="center" prop="secretPeroid">
        <template #default="scope">
          <dict-tag :options="iams_secret_period" :value="scope.row.secretPeroid" />
        </template>
      </el-table-column>
      <el-table-column label="解密日期" align="center" prop="desecretDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.desecretDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保管期限" align="center" prop="retentionPeriod">
        <template #default="scope">
          <dict-tag :options="iams_retention_period" :value="scope.row.retentionPeriod" />
        </template>
      </el-table-column>
      <el-table-column label="载体类型" align="center" prop="carrierType" width="180">
        <template #default="scope">
          <dict-tag :options="iams_carrier_type" :value="scope.row.carrierType" />
        </template>
      </el-table-column>
      <el-table-column label="起始时间" align="center" prop="startDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="终止时间" align="center" prop="endDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归档时间" align="center" prop="guidangTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.guidangTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="形成单位" align="center" prop="formationUnit" />
      <el-table-column label="移交单位" align="center" prop="transferUnit" />
      <el-table-column label="档案状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="iams_archive_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="档案门类" align="center" prop="categoryId" />
      <el-table-column label="档案全宗" align="center" prop="fondsId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:archive:edit']">修改</el-button>
          <el-button link type="primary" @click="handleMount()" v-hasPermi="['manage:archive:edit']">挂接</el-button>
          <el-button link type="primary" @click="showExtraInfo()">查看额外信息</el-button>
          <el-button link type="primary" @click="handleBatchUpload">批量上传文档</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-divider />
    <!-- 使用element plus的网格布局方式把下面的区域分为两列，左边展示档案目录，右边展示目录里面的文件列表 -->
    <el-row :gutter="2">
      <el-col :span="5">
        <el-card style="max-width: 100%;">
          <template #header>
            <div class="card-header"
              style="display: flex; flex-direction: row;justify-content: space-between; align-items: center;">
              <el-text size="large" tag="b">档案目录结构</el-text>
              <el-link type="primary" size="mini" @click="getDocumentList()">所有文档</el-link>
            </div>
          </template>
          <el-tree :data="dataSource" :props="defaultProps" node-key="id" default-expand-all :highlight-current="true"
            :expand-on-click-node="false" icon="Folder" @node-click="handleNodeClick">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ data.id }}-{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-table v-loading="loading" :data="filteredDocumentList">
          <el-table-column label="主键" align="center" prop="id" />
          <el-table-column label="文件名称" align="center" prop="name">
            <template #default="{ row }">
              <span v-html="row.name"></span> <!-- 修改：允许渲染高亮HTML -->
            </template>
          </el-table-column>
          <el-table-column label="文件类型" align="center" prop="fileType" />
          <el-table-column label="文件大小(Kb)" align="center" prop="fileSize" />
          <el-table-column label="所在目录" align="center" prop="directory" />
          <el-table-column label="文件路径" align="center" prop="filePath" />
          <el-table-column label="存放位置" align="center" prop="fileLocation" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" @click="handleDocumentDetail(scope.row)"
                v-hasPermi="['manage:document:query']">查看</el-button>
              <el-button link type="primary" @click="removeDocument(scope.row)"
                v-hasPermi="['manage:document:remove', 'manage:document:edit']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getDocumentList" />
      </el-col>
    </el-row>

    <!-- 额外信息对话框 -->
    <el-dialog title="额外信息" v-model="extraInfoDialog" width="500px" append-to-body class="enhanced-extra-info-dialog">
      <div class="enhanced-extra-info-container">
        <el-scrollbar max-height="400px">
          <div v-for="(item, index) in extraInfo" :key="index" class="enhanced-extra-info-item"
            :class="{ 'last-item': index === extraInfo.length - 1 }">
            <div class="info-label">
              <el-tag type="info" size="small">{{ item.label }}</el-tag>
            </div>
            <div v-html="DOMPurify.sanitize(item.value)" class="info-content"></div>
          </div>
        </el-scrollbar>
      </div>

      <template #footer>
        <div class="enhanced-dialog-footer">
          <el-button @click="extraInfoDialog = false" type="primary" size="small">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getArchive, deleteDirectoryFiles } from "@/api/manage/archive";
import { listDocument, listDocumentByIds, delDocument, getDocument } from "@/api/manage/document";
import DOMPurify from 'dompurify'

const { proxy } = getCurrentInstance();
const { iams_carrier_type, iams_archive_status, iams_retention_period, iams_secret_period, iams_secret_level } = proxy.useDict('iams_carrier_type', 'iams_archive_status', 'iams_retention_period', 'iams_secret_period', 'iams_secret_level');

const route = useRoute();

// ================= 新增状态 =================
const isFromSearch = computed(() => route.query.fromSearch === 'true') // 是否来自搜索跳转
const searchText = ref(route.query.searchText || '') // 搜索关键词
const searchField = ref(route.query.searchField || '') // 搜索字段
const highlights = ref(route.query.highlights ? JSON.parse(route.query.highlights) : {}) // ES高亮数据
const filteredDocumentList = ref([]) // 处理后的文档列表（高亮+排序）

const archive = ref({});
const archiveList = ref([]);
const dataSource = ref([]);

const documentList = ref([]);
const loading = ref(true);
const total = ref(0);
const queryParams = ref({
  archiveId: route.query.id,
  pageNum: 1,
  pageSize: 10,
});

const defaultProps = {
  id: 'id',
  label: 'label',
  files: [],
  children: 'children',
}

const extraInfoDialog = ref(false)
const extraInfo = ref([])

// 工具函数：安全高亮文本
const highlightText = (text, keyword) => {
  if (!text || !keyword) return text;
  const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 转义正则特殊字符
  const regex = new RegExp(escapedKeyword, 'gi');
  return text.replace(regex, match => `<span class="search-highlight">${match}</span>`);
};
/**
 * 处理文档列表（高亮+排序）
 */
const processDocumentList = (list) => {
  if (!route.query.fromSearch || !route.query.searchText) return list;

  const searchText = route.query.searchText;
  return list.map(doc => {
    const processedDoc = { ...doc }; // 浅拷贝
    // 高亮文档名称
    processedDoc.name = highlightText(doc.name, searchText);
    return processedDoc;
  }).sort((a, b) => {
    // 匹配关键词的文档置顶
    const aMatch = a.name?.toLowerCase().includes(searchText.toLowerCase());
    const bMatch = b.name?.toLowerCase().includes(searchText.toLowerCase());
    return (bMatch ? 1 : 0) - (aMatch ? 1 : 0);
  });
};

/**
 * 递归收集数据及其子项中的所有文件ID
 * @param {Object} data - 当前数据对象，包含 files 和 children 属性
 * @returns {Array} - 包含所有文件ID的数组
 */
function collectFileIds(data) {

  console.log(data);

  let fileIds = [];

  fileIds = fileIds.concat(data.files);

  // 递归收集子项中的文件ID
  if (data.children && data.children.length > 0) {
    data.children.forEach(child => {
      fileIds = fileIds.concat(collectFileIds(child));
    });
  }
  console.log(fileIds);
  return fileIds;
}

const handleNodeClick = (data) => {
  const fileids = collectFileIds(data).join(',');
  if (fileids == '') {
    filteredDocumentList.value = [];
    return;
  }
  loading.value = true;
  listDocumentByIds({ ids: fileids }).then(response => {
    // 应用高亮和排序
    filteredDocumentList.value = processDocumentList(response.rows);
    total.value = response.total;
    loading.value = false;
  })
};
//
// function getDocumentList() {
//   loading.value = true;
//   listDocument(queryParams.value).then(response => {
//     documentList.value = response.rows;
//     filteredDocumentList.value = processDocumentList(response.rows) // 新增处理步骤
//     total.value = response.total;
//     loading.value = false;
//   });
// }

function getDocumentList() {
  loading.value = true;

  // ▼▼▼ 修改：如果是搜索跳转，获取所有数据再分页 ▼▼▼
  if (isFromSearch.value && searchText.value) {
    // 临时获取所有数据（不分页）
    listDocument({
      ...queryParams.value,
      pageNum: 1,
      pageSize: 10000 // 临时调大size获取全部数据
    }).then(response => {
      // 全局排序
      const sortedList = processDocumentList(response.rows);
      // 手动分页
      const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
      filteredDocumentList.value = sortedList.slice(start, start + queryParams.value.pageSize);
      total.value = sortedList.length; // 使用排序后的总条数
      loading.value = false;
    });
  } else {
    // 普通分页查询
    listDocument(queryParams.value).then(response => {
      filteredDocumentList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
  // ▲▲▲ 修改结束 ▲▲▲
}

onMounted(() => {
  const archiveId = route.query.id;
  getArchive(archiveId).then(response => {

    if (route.query.fromSearch && route.query.highlights) {
      const highlights = JSON.parse(route.query.highlights);
      if (highlights.title) response.data.title = highlights.title[0];
      if (highlights.description) response.data.description = highlights.description[0];
    }
    archive.value = response.data;
    dataSource.value = JSON.parse(archive.value.directory);
    // 把archive加入到archiveList列表中
    archiveList.value.push(archive.value);
    getDocumentList();
  });



});

/** 修改档案操作 */
function handleUpdate(row) {
  proxy.$router.push({ path: "/manage/archive/arc-edit", query: { id: row.id } });
}

/** 档案挂接文档操作 */
function handleMount() {
  proxy.$router.push({ path: "/manage/archive/arc-mount", query: { id: archive.value.id } });
}

function handleDocumentDetail(row) {
  proxy.$router.push({ path: "/manage/document/doc-detail", query: { id: row.id } });
}

function removeDocument(row) {
  deleteDirectoryFiles(row).then(res => {
    if (res.code == 200) {
      delDocument(row.id);
      proxy.$modal.msgSuccess("删除成功");
      getDocumentList();
    } else {
      proxy.$modal.msgError(res.msg);
    }
  });
}

function showExtraInfo() {
  extraInfoDialog.value = true
  extraInfo.value = JSON.parse(archive.value.extraInfo)
}

function handleBatchUpload() {
  proxy.$router.push({ path: '/manage/document/import', query: { archiveId: route.query.id } });
}
</script>

<style scoped>
.search-highlight {
  background-color: yellow;
  color: red;
  font-weight: bold;
  padding: 0 2px;
  border-radius: 2px;
}

.enhanced-extra-info-dialog {
  border-radius: 8px;
}

.enhanced-extra-info-container {
  padding: 0 10px;
}

.enhanced-extra-info-item {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.enhanced-extra-info-item.last-item {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.info-label {
  margin-bottom: 8px;
}

.info-content {
  padding-left: 8px;
  line-height: 1.6;
  color: #333;
}

.enhanced-dialog-footer {
  text-align: center;
  padding-top: 10px;
}
</style>